echo off
rem MSYS2 安装脚本
rem MSYS2 下载 http://repo.msys2.org/distrib/x86_64/msys2-base-x86_64-20161025.tar.xz
set sh_folder=%~dp0
set sh_folder=%sh_folder:~0,-1%
rem bin 文件夹加入搜索路径,后面的脚本中用到bin中的命令(wget,md5sum,xz,tar...)
set PATH=%sh_folder%\bin;%PATH%	
pushd %sh_folder%

set msys2_version=x86_64-20161025
set msys2_chksum=c1598fe0591981611387abee5089dd1f
rem set msys2_chksum=2799d84b4188b8faa772be6f80db9f45
set msys2_package=msys2-base-%msys2_version%.tar.xz
set msys2_url=http://repo.msys2.org/distrib/x86_64/%msys2_package%
rem url=http://repo.msys2.org/distrib/i686/%msys2_package%

set folder_name=msys64

if exist %folder_name% goto :eof
call :download_msys2

rem 解压 .tar.xz
xz -d %msys2_package%	
call :exit_on_error

rem 解压 .tar
tar xvf %msys2_package:~0,-3%	
call :exit_on_error

rem 删除 .tar
del %msys2_package:~0,-3%	-f
call :exit_on_error

call :init_msys2

popd

goto :eof

rem 当上一条命令出错时中止脚本执行
:exit_on_error
if NOT ERRORLEVEL 0 exit /B -1
goto :eof

rem 下载源码
:download_msys2
if not exist %msys2_package% set need_download=0

rem 对于已经存在的文件,判断checksum是否相同,不相同则删除重新下载
if exist %msys2_package% (	
	rem for %%s in ('md5sum %msys2_package% | awk "{ print $1 }"') do set checksum=%%s
	for /f %%s in ('md5sum %msys2_package%') do set checksum=%%s
	pause
	echo checksum     =%checksum%
	echo msys2_chksum =%msys2_chksum%
	if "%checksum%" EQU "%msys2_chksum%" set need_download=1 
	if "%checksum%" NEQ "%msys2_chksum%" (
		set need_download=0
		del "%msys2_package%"
		call :exit_on_error 
		)
	)
if  %need_download% EQU 0 (
	wget %msys2_url%
	call :exit_on_error
	)

goto :eof

rem 在MSYS2 bash shell中执行MSYS2自身的初始化和thrift编译依赖库安装
:init_msys2

rem  安装thrift依赖库和必须的工具
rem pacman --needed --noconfirm -S unzip bison flex make mingw-w64-x86_64-openssl \
rem             mingw-w64-x86_64-boost mingw-w64-x86_64-cmake \
rem             mingw-w64-x86_64-toolchain mingw-w64-x86_64-zlib
set init_cmd="pacman --needed --noconfirm -S unzip bison flex make mingw-w64-x86_64-openssl mingw-w64-x86_64-boost mingw-w64-x86_64-cmake mingw-w64-x86_64-toolchain mingw-w64-x86_64-zlib"

%folder_name%\usr\bin\bash -l -c %init_cmd%

goto :eof
